package com.zgt.web.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;
import com.zgt.model.Student;
import com.zgt.model.Teacher;
import com.zgt.model.Topic;
import com.zgt.service.StudentService;
import com.zgt.util.ExcelUtil;
import com.zgt.util.MD5;
import com.zgt.util.Page;
import com.zgt.util.ToExcel;
import com.zgt.web.AbstractAction;

@Controller("studentAction")
@Scope("prototype")
@SuppressWarnings("unchecked")
public class StudentAction extends AbstractAction implements
		ModelDriven<Student> {

	private String key;

	private String keyType;
	private MD5 m = new MD5();
	private Page page = new Page();
	private Map request = (Map) ActionContext.getContext().get("request");
	private Map session = ActionContext.getContext().getSession();
	private Student student = new Student();
	private StudentService studentService;

	private String submitFlag;
	private Teacher teacher = new Teacher();
	private int teacher_id;

	private Topic topic = new Topic();

	private int topic_id;
	private File uploadExcle;
	private String uploadExcleContentType;
	private String uploadExcleFileName;

	public String add() {
		if (submitFlag == null) {
			return INPUT;
		}
		studentService.addStudent(student);
		request.put("url", "student_list.action");
		return SUCCESS;
	}

	public String batch() {
		if (submitFlag == null) {
			return INPUT;
		}
		List temList;
		String realpath = (ServletActionContext.getServletContext()
				.getRealPath("/upload"));
		File file = new File(realpath);
		File newFile = new File(file, uploadExcleFileName);
		if (!file.exists())
			file.mkdirs();
		try {
			FileUtils.copyFile(uploadExcle, newFile);

			temList = ToExcel.readExcel(newFile);

			studentService.addStudents(temList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.put("url", "student_list.action");
		return SUCCESS;
	}

	public String delete() {
		studentService.deleteStudentById(student.getId());
		return SUCCESS;
	}

	public String edit() {
		if (submitFlag == null) {
			student = studentService.getStudentById(student.getId());
			request.put("student", student);
			return INPUT;
		}
		if (!student.getPassword().trim().isEmpty()
				&& student.getPassword() != null) {
			student.setPassword(m.getMD5ofStr(student.getPassword()));
		} else {
			Student temp = studentService.getStudentById(student.getId());
			student.setPassword(temp.getPassword());
		}
		studentService.updateStudent(student);
		request.put("url", "student_list.action");

		return SUCCESS;
	}

	@Override
	public String execute() throws Exception {
		return super.execute();
	}

	public String getKey() {
		return key;
	}

	public String getKeyType() {
		return keyType;
	}

	public Student getModel() {
		return student;
	}

	public Page getPage() {
		return page;
	}

	public String getSubmitFlag() {
		return submitFlag;
	}

	public int getTeacher_id() {
		return teacher_id;
	}

	public int getTopic_id() {
		return topic_id;
	}

	public File getUploadExcle() {
		return uploadExcle;
	}

	public String getUploadExcleContentType() {
		return uploadExcleContentType;
	}

	public String getUploadExcleFileName() {
		return uploadExcleFileName;
	}

	public String info() {
		student = (Student) session.get("user");
		student = studentService.getStudentById(student.getId());
		request.put("student", student);
		return INPUT;
	}

	public String information() {
		student = studentService.getStudentById(student.getId());
		request.put("student", student);
		return INPUT;
	}

	public String list() {
		request.put("page", studentService.listStudent(page));
		return INPUT;
	}

	public String login() {
		student.setStudentNum(student.getStudentNum());
		student.setPassword(m.getMD5ofStr(student.getPassword()));
		student = studentService.checkLogin(student);
		if (student != null) {
			session.put("user", student);
			session.put("scope", "student");
			return "login";
		}
		return ERROR;
	}

	public String logout() {
		session.clear();
		return ERROR;
	}

	public String modify() {
		if (submitFlag == null) {
			student = (Student) session.get("user");
			student = studentService.getStudentById(student.getId());
			request.put("student", student);
			return INPUT;
		}
		if (!student.getPassword().trim().isEmpty()
				&& student.getPassword() != null) {
			student.setPassword(m.getMD5ofStr(student.getPassword()));
		} else {
			Student temp = studentService.getStudentById(student.getId());
			student.setPassword(temp.getPassword());
		}
		studentService.updateStudent(student);
		request.put("url", "student_modify.action");
		return SUCCESS;
	}

	public String search() {
		studentService.listSearch(page, key, keyType);
		request.put("key", key);
		request.put("keyType", keyType);
		return INPUT;
	}

	public String select() {
		request.put("page", studentService.listSelect(page));
		return INPUT;
	}

	public String selectToExcle() {
		
		return INPUT;
	}
	
	public void selectToExcles(){
		List<Student> list = studentService.selectToExcle(keyType);
		Iterator<Student> iter = list.iterator();

		String title;
		if("className".equals(keyType)){
			title="OutPut by Class Name";
		}else{
			title="OutPut by Class Major";
		}
		download(list, title, keyType);
		
		
	}

	public String selectTeacher() {
		student = (Student) session.get("user");
		teacher.setId(teacher_id);
		student.setTeacher(teacher);
		studentService.selectTeacher(student, teacher);
		request.put("url", "teacher_list.action");
		return SUCCESS;
	}

	public String reSelectTeacher() {
		student = (Student) session.get("user");
		teacher = student.getTeacher();
		student.setTeacher(null);
		studentService.reSelectTeacher(student, teacher);
		request.put("url", "teacher_list.action");
		return SUCCESS;
	}

	public String selectTopic() {
		student = (Student) session.get("user");
		student = studentService.getStudentById(student.getId());
		topic.setId(topic_id);
		student.setTopic(topic);
		studentService.selectTopic(student, topic);
		request.put("url", "topic_list.action");
		session.put("user", student);
		return SUCCESS;
	}

	public String reSelectTopic() {
		student = (Student) session.get("user");
		topic.setId(student.getTopic().getId());
		student.setTopic(null);
		studentService.reSelectTopic(student, topic);
		request.put("url", "topic_list.action");
		return SUCCESS;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public void setKeyType(String keyType) {
		this.keyType = keyType;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	@Resource
	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}

	public void setSubmitFlag(String submitFlag) {
		this.submitFlag = submitFlag;
	}

	public void setTeacher_id(int teacher_id) {
		this.teacher_id = teacher_id;
	}

	public void setTopic_id(int topic_id) {
		this.topic_id = topic_id;
	}

	public void setUploadExcle(File uploadExcle) {
		this.uploadExcle = uploadExcle;
	}

	public void setUploadExcleContentType(String uploadExcleContentType) {
		this.uploadExcleContentType = uploadExcleContentType;
	}

	public void setUploadExcleFileName(String uploadExcleFileName) {
		this.uploadExcleFileName = uploadExcleFileName;
	}

	public void toExcle() {
		List<Student> students = studentService.toExcle(key, keyType);
		download(students, "", null);
	}

	private void download(List<Student> students, String key, String keyType) {
		HttpServletResponse response = ServletActionContext.getResponse();
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("Sheet1");
		String[] tableHeader = new String[11];

		ExcelUtil.setCellValue(sheet, 0, 1, "Id");
		ExcelUtil.setCellValue(sheet, 1, 1, "学号");
		ExcelUtil.setCellValue(sheet, 2, 1, "姓名");
		ExcelUtil.setCellValue(sheet, 3, 1, "性别");
		ExcelUtil.setCellValue(sheet, 4, 1, "专业");
		ExcelUtil.setCellValue(sheet, 5, 1, "班级");
		ExcelUtil.setCellValue(sheet, 6, 1, "毕业设计题目");
		ExcelUtil.setCellValue(sheet, 7, 1, "指导老师");
		ExcelUtil.setCellValue(sheet, 8, 1, "联系电话");
		ExcelUtil.setCellValue(sheet, 9, 1, "QQ号码");
		ExcelUtil.setCellValue(sheet, 10, 1, "Email");

		int t = 0;
		for (int i = 2; i < students.size() + 2; i++) {
			Student student = (Student) students.get(t);

			ExcelUtil.setCellValue(sheet, 0, i, student.getId() + "");
			ExcelUtil.setCellValue(sheet, 1, i, student.getStudentNum());
			ExcelUtil.setCellValue(sheet, 2, i, student.getName());
			ExcelUtil.setCellValue(sheet, 3, i, student.getSex());
			ExcelUtil.setCellValue(sheet, 4, i, student.getMajor());
			ExcelUtil.setCellValue(sheet, 5, i, student.getClassName());
			ExcelUtil.setCellValue(sheet, 6, i, student.getTopic() == null ? ""
					: student.getTopic().getName());
			ExcelUtil.setCellValue(sheet, 7, i,
					student.getTeacher() == null ? "" : student.getTeacher()
							.getName());
			ExcelUtil.setCellValue(sheet, 8, i, student.getTelphone());
			ExcelUtil.setCellValue(sheet, 9, i, student.getQq());
			ExcelUtil.setCellValue(sheet, 10, i, student.getEmail());

			t++;

		}
		ExcelUtil.createTitle(sheet, tableHeader);
		if (key != null) {
			try {
				ExcelUtil.print2003Excel(wb, response, key, keyType);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void validate() {
		if (submitFlag == null) {
			return;
		}
		if ("upload".equals(submitFlag)) {
			return;
		}

	}

}
